/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  SupervisionBusiStaffActivity.java   
 * @Package com.jiyi.activity.supervision   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-10-21 下午2:26:55   
 * @version V1.0     
 */
package com.jiyi.activity.supervision;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.CommonAdapter;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.supervision.SupervisionPeopleBean;
import com.jiyi.bean.weibao.CompanyBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.SupervisionAuthorityEvent;
import com.jiyi.inteface.WebApi;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: SupervisionBusiStaffActivity
 * @Description:TODO(业务查询-参谋)
 * @author: HYM
 * @date: 2017-10-21 下午2:26:55
 * 
 */
public class SupervisionBusiStaffActivity extends ActivityBase implements
		OnRefreshListener {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.ivPeople)
	ImageView ivPeople;
	@BindView(R.id.ivSearch)
	ImageView ivSearch;
	@BindView(R.id.etSearch)
	EditText etSearch;

	LayoutInflater inflater;
	@BindView(R.id.mainList)
	RecyclerView mainList;
	@BindView(R.id.refreshLayout)
	SwipeRefreshLayout refreshLayout;
	EmptyWrapper adapter;
	private List<SupervisionPeopleBean> peopleDataList = new ArrayList<SupervisionPeopleBean>();
	private List<CompanyBean> ownerDataList = new ArrayList<CompanyBean>();
	ViewGroup container;

	// 监管大队的id,name,被查看的用户id
	String up_id, staff_name,user_id;
	// 查看的类别 1 人员类别、2 业主类别
	int type = 1;
	// 该模块应用于哪个功能 1 业务查询 2 权限设置
	private int func;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_supervision_busi_staff);
		ButterKnife.bind(this);
		init();
	}

	private void init() {
		getIntentData();
		inflater = LayoutInflater.from(this);
		setTop();
		initViewState();
		// 设置refreshLayout的监听
		refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
				Color.GREEN);
		refreshLayout.setOnRefreshListener(this);

		mainList.setLayoutManager(new LinearLayoutManager(this));
		mainList.addItemDecoration(new DividerItemDecoration(this,
				DividerItemDecoration.VERTICAL_LIST, null));
		setAdapter(type);
		getData(type);
		EventBus.getDefault().register(this);
	}
	
	

	@Subscribe
	public void onSupervisionAuthorityEvent(
			SupervisionAuthorityEvent supervisionAuthorityEvent) {
		for (int i = 0; i < peopleDataList.size(); i++) {
			if (supervisionAuthorityEvent.user_id.equals(peopleDataList.get(i)
					.getUser_id())) {
				peopleDataList.remove(i);
				adapter.notifyDataSetChanged();
				break;
			}
		}
	}

	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	private void getIntentData() {
		user_id = getIntent().getStringExtra("user_id");
		up_id = getIntent().getStringExtra("up_id");
		staff_name = getIntent().getStringExtra("staff_name");
		func = getIntent().getIntExtra("func", 1);
	}

	private void setTop() {
		tvTitle.setText(staff_name);
		if (func == 1) {
			ivPeople.setImageResource(R.mipmap.icon_tool_wb);
		} else {
			ivPeople.setVisibility(View.GONE);
		}

		ivSearch.setVisibility(View.GONE);
	}
	
	private void initViewState() {
		// 设置输入法的搜索事件
		etSearch.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH
						|| actionId == EditorInfo.IME_ACTION_DONE) {
					InputMethodManager imm = (InputMethodManager) v
							.getContext().getSystemService(
									Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);

					Log.e("onEditorAction  ", "   done ");
					getData(type);
					return true;
				}
				return false;
			}
		});

	}

	private void setAdapter(int type) {
		CommonAdapter mCommonAdapter;
		if (type == 1) {
			mCommonAdapter = new CommonAdapter<SupervisionPeopleBean>(this,
					R.layout.item_supervision_people, peopleDataList) {
				@Override
				protected void convert(ViewHolder holder,
						final SupervisionPeopleBean t, int position) {

					holder.setText(R.id.tvSuperPeople, t.getUser_name());
					holder.setText(R.id.tvDuty, t.getPosition());
					holder.setText(R.id.tvTel, t.getMobile());

					holder.setOnClickListener(R.id.rlRoot,
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									if (func == 1) {
										Intent intent = new Intent(
												v.getContext(),
												SupervisionBusiAllOwnerActivity.class);
										intent.putExtra("func", 2);
										intent.putExtra("user_id", t.getUser_id());
										startActivity(intent);
									} else {
										Intent intent = new Intent(
												v.getContext(),
												SupervisionAuthorityActivity.class);
										intent.putExtra("user_id",
												t.getUser_id());
										startActivity(intent);
									}

								}
							});
				}
			};

		} else {
			mCommonAdapter = new CommonAdapter<CompanyBean>(this,
					R.layout.item_supervision_owner_add, ownerDataList) {
				@Override
				protected void convert(ViewHolder holder, final CompanyBean t,
						int position) {
					holder.setText(R.id.tvOwnerName, t.getName());
					holder.setText(R.id.tvOwnerPhone, t.getPhone());
					holder.setText(R.id.tvOwnerAddress, t.getAddress());

					holder.setImage(
							R.id.ivLogo,
							t.getCompany_logo() == null ? "" : t
									.getCompany_logo());

					holder.setOnClickListener(R.id.rlRoot,
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									Intent intent = new Intent(v.getContext(),
											SupervisionBusiDetailActivity.class);
									intent.putExtra("owner_id", t.getId());
									startActivity(intent);
								}
							});
				}
			};
		}

		adapter = new EmptyWrapper(mCommonAdapter);

		View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
				mainList, false);
		ImageView ivEmptyTip = (ImageView) emptyView
				.findViewById(R.id.ivEmptyTip);
		TextView tvEmptyTip = (TextView) emptyView
				.findViewById(R.id.tvEmptyTip);
		ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
		tvEmptyTip.setText(R.string.NO_DATA);
		adapter.setEmptyView(emptyView);

		mainList.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	private void getData(final int type) {
		String url = "";
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());

		if (!TextUtils.isEmpty(etSearch.getText().toString())) {
			params.put("u_name",etSearch.getText().toString());
		}
		
		if (type == 1) {
			url = WebApi.SUPERVISION_BUSI_ASSI_LIST;
			params.put("up_id", up_id);
		} else {
			
//			params.put("com_name", "");
			params.put("user_id", user_id);
			url = WebApi.SUPERVISION_BUSI_NEXT_OWNER_LIST;
		}

		VolleyRequest.StringRequestPost(this, url, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");

								if (type == 1) {
									JSONObject dataJson = new JSONObject(data);
									SupervisionPeopleBean self = new Gson().fromJson(dataJson.get("userRecord").toString(), SupervisionPeopleBean.class);
									List<SupervisionPeopleBean> temp = new Gson()
											.fromJson(
													dataJson.get("superLists").toString(),
													new TypeToken<List<SupervisionPeopleBean>>() {
													}.getType());
									peopleDataList.clear();
									peopleDataList.add(self);
									peopleDataList.addAll(temp);
									adapter.notifyDataSetChanged();
								} else {
									List<CompanyBean> temp = new Gson()
											.fromJson(
													data,
													new TypeToken<List<CompanyBean>>() {
													}.getType());
									ownerDataList.clear();
									ownerDataList.addAll(temp);
									adapter.notifyDataSetChanged();
								}

							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							refreshLayout.setRefreshing(false);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						refreshLayout.setRefreshing(false);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	@OnClick({ R.id.tvBack, R.id.ivSearch, R.id.ivPeople })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.ivSearch:

			break;
		case R.id.ivPeople:
			if (type == 1) {
				type = 2;
				ivPeople.setImageResource(R.mipmap.icon_busi_area);
			} else {
				type = 1;
				ivPeople.setImageResource(R.mipmap.icon_tool_wb);
			}
			adapter = null;
			setAdapter(type);
			onRefresh();
			break;
		default:
			break;
		}
	}

	@Override
	public void onRefresh() {
		getData(type);
	}
}
